
//
//  HomePageViewController.m
//  ChineseCollegeStudentsNetwork
//
//  Created by 刘喆 on 2018/5/9.
//  Copyright © 2018年 刘喆. All rights reserved.
//

#import "HomePageViewController.h"
#import "SharedViewCell.h"
#import "BannerView.h"
#import "SectionView.h"
#import "ArticleViewCell.h"
#import "SelectionViewCell.h"
#import "SchoolViewCell.h"
#import "SJNetworkHelper.h"
#import "LLSegmentBar.h"
#import "AddressViewController.h"
#import "MLAWebVC.h"
#import "UserCenterViewController.h"
#import "LoginViewController.h"

static NSString *kSharedViewCell = @"SharedViewCell";
static NSString *kSelectionViewCell = @"SelectionViewCell.h";
static NSString *kSchoolViewCell = @"SchoolViewCell.h";
static NSString *kArticleViewCell = @"ArticleViewCell";

@interface HomePageViewController ()<UITableViewDelegate,UITableViewDataSource,LLSegmentBarDelegate,UITabBarControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) BannerView *headView;
@property (nonatomic, strong) SchoolViewCell *schoolViewCell;
@property (nonatomic, strong) LLSegmentBar *segmentBar;

@property (nonatomic, strong) NSArray *models1;
@property (nonatomic, strong) NSArray *models2;
@property (nonatomic, strong) NSArray *models3;
@property (nonatomic, strong) NSArray *models4;
@property (nonatomic, strong) NSArray *models5;

@property (nonatomic, strong) BaseNavigationController *selectedNav;


@end

@implementation HomePageViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}


- (BannerView *)headView {
    if(!_headView){
        _headView = [[BannerView alloc] init];
        CGFloat height = 0;
        height = self.view.frame.size.width/1.875 + 30;
        _headView.frame = CGRectMake(0, 0, 0, height);
        
        _headView.clickBannerBlock = ^(NSInteger index) {
            CommonModel *model = _models3[index];
            MLAWebVC *webVC = [[MLAWebVC alloc] init];
            webVC.urlStr = model.navigationUrl;
            webVC.titleStr = model.title;
            [self.navigationController pushViewController:webVC animated:YES];
        };
        
        _headView.clickTitleBlock = ^(NSInteger index) {
            CommonModel *model = _models5[index];
            MLAWebVC *webVC = [[MLAWebVC alloc] init];
            webVC.urlStr = model.navigationUrl;
            webVC.titleStr = model.title;
            [self.navigationController pushViewController:webVC animated:YES];
        };
    }
    return _headView;
}

- (LLSegmentBar *)segmentBar {
    
    if (!_segmentBar) {
        
        _segmentBar = [[LLSegmentBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        _segmentBar.delegate = self;
        _segmentBar.items = @[@"新闻",@"校园",@"留学",@"职场",@"更多"];
    }
    return _segmentBar;
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    BaseNavigationController *nav = (BaseNavigationController *)viewController;
    NSLog(@"%@",nav.topViewController);

    if ([nav.topViewController isKindOfClass:[UserCenterViewController class]] && (!kGetToken)) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [_selectedNav pushViewController:loginVC animated:YES];
        return NO;
    } else {
        _selectedNav = nav;
    }
    
    
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"首页";

    _selectedNav = (BaseNavigationController *)self.navigationController;
    
    self.tabBarController.delegate = self;
    
    [self setupConstraints];

    [self requestForDataSourceOfModule:RequestModuleTypeMagazine size:0];
    [self requestForDataSourceOfModule:RequestModuleTypeSpecialReport size:0];
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Get hostType:MLAHttpHostType_Api api:@"/api/v1/stl/contents" params:@{@"channelName":@"首页Banner"} success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        _models3 = [CommonModel mj_objectArrayWithKeyValuesArray:[(NSDictionary *)response objectForKey:@"value"]];
        NSMutableArray *listArr = [NSMutableArray array];
        for (CommonModel *model in _models3) {
            [listArr addObject:model.imageUrl];
        }
        _headView.dataArray = listArr;
        
    } failure:^{
        
    }];
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Get hostType:MLAHttpHostType_Api api:@"/api/v1/contents/32/100" params:@{@"top":@"1"} success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        _models4 = [CommonModel mj_objectArrayWithKeyValuesArray:[(NSDictionary *)response objectForKey:@"value"]];
        [self.tableView reloadData];

    } failure:^{
        
    }];
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Get hostType:MLAHttpHostType_Api api:@"/api/v1/contents/32/33" params:nil success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        _models5 = [CommonModel mj_objectArrayWithKeyValuesArray:[(NSDictionary *)response objectForKey:@"value"]];
        NSMutableArray *listArr = [NSMutableArray array];
        for (CommonModel *model in _models5) {
            [listArr addObject:model.title];
        }
        _headView.titlesArr = listArr;

    } failure:^{
        
    }];
    
}

#pragma mark - Network

- (void)requestForDataSourceOfModule:(RequestModuleType)moduleType size:(NSUInteger)size {
    
    [[SJNetworkHelper sharedManager] getDataInModule:moduleType toalNum:size success:^(NSArray<CommonModel *> *models) {
        
        switch (moduleType) {
                
            case RequestModuleTypeMagazine: {
                
                _models1 = [models copy];
                
                [self.tableView reloadData];
                break;
            }
            case RequestModuleTypeNews:
            case RequestModuleTypeSchool:
            case RequestModuleTypeStudyAbroad:
            case RequestModuleTypeJob:
            case RequestModuleTypeMore: {
                [self.schoolViewCell.dataSource removeAllObjects];
                [self.schoolViewCell.dataSource addObjectsFromArray:models];
                [self.schoolViewCell.collectionView reloadData];
                break;
            }
            case RequestModuleTypeSpecialReport: {
                
                _models2 = [models copy];
                [self.tableView reloadData];
                break;
            }
            default:break;
        }
        
    } failure:^(NSError *err){
        ShowMessage(@"网络请求失败");
    }];
}

#pragma mark - UI


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0.001;
        _tableView.estimatedSectionHeaderHeight = 0.001;
        [_tableView registerClass:[SharedViewCell class] forCellReuseIdentifier:kSharedViewCell];
        [_tableView registerClass:[SelectionViewCell class] forCellReuseIdentifier:kSelectionViewCell];
        [_tableView registerClass:[SchoolViewCell class] forCellReuseIdentifier:kSchoolViewCell];
        [_tableView registerClass:[ArticleViewCell class] forCellReuseIdentifier:kArticleViewCell];
        self.headView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _tableView.tableHeaderView = self.headView;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}

- (void)setupConstraints {
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        SharedViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSharedViewCell forIndexPath:indexPath];
        cell.dataSource = _models1;

        return cell;
    } else if (indexPath.section == 1) {
        SelectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSelectionViewCell forIndexPath:indexPath];
        CommonModel *model = _models4[indexPath.row];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.imageUrl] placeholderImage:[UIImage imageNamed:@"飞艇"]];
        return cell;
    } else if (indexPath.section == 2) {
        if (!self.schoolViewCell) {
            self.schoolViewCell = [tableView dequeueReusableCellWithIdentifier:kSchoolViewCell forIndexPath:indexPath];
            [self requestForDataSourceOfModule:RequestModuleTypeNews size:0];
        }
        return self.schoolViewCell;
    } else if (indexPath.section == 3) {
        ArticleViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kArticleViewCell forIndexPath:indexPath];
        cell.dataSource = _models2;
        return cell;
        
    }
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2) {
        SchoolViewCell *cell = (SchoolViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell.collectionView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 1 ? 0.001 : 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 3 ? 0.0001 : 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 176;
    } else {
        return 146;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SectionView *sectionView = [[SectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    sectionView.titleLabel.textColor = kColorTint;
    if (section == 0 ) {
        sectionView.titleLabel.text = @"往期杂志";
        return sectionView;
    }else if (section == 2) {
        return self.segmentBar;
    }else if (section == 3) {
        sectionView.titleLabel.text = @"热门文章";
        return sectionView;
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        CommonModel *model = _models4[indexPath.row];
        MLAWebVC *webVC = [[MLAWebVC alloc] init];
        webVC.titleStr = model.title;
        webVC.urlStr = model.navigationUrl;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

#pragma mark - LLSegmentBarDelegate

-(void)segmentBar:(LLSegmentBar *)segmentBar didSelectIndex:(NSInteger)toIndex fromIndex:(NSInteger)fromIndex {
    
    if (toIndex == fromIndex) return;
    
    [self.schoolViewCell.dataSource removeAllObjects];
    [self.schoolViewCell.collectionView reloadData];
    
    switch (toIndex) {
        case 0:
            [self requestForDataSourceOfModule:RequestModuleTypeNews size:0];
            break;
        case 1:
            [self requestForDataSourceOfModule:RequestModuleTypeSchool size:0];
            break;
        case 2:
            [self requestForDataSourceOfModule:RequestModuleTypeStudyAbroad size:0];
            break;
        case 3:
            [self requestForDataSourceOfModule:RequestModuleTypeJob size:0];
            break;
        case 4:
            [self requestForDataSourceOfModule:RequestModuleTypeMore size:0];
            break;
        default:
            break;
    }
    
}

@end
